/* 获取当前页面最顶层即时贴z-index值 */
function getMaxZIndex(){
    var zIndex;
    var maxZIndex=0;
    $(".note").each(function(){
        zIndex = $(this).css("z-index");
        if(parseInt(zIndex)>maxZIndex){
            maxZIndex = zIndex;
        }
    });
    return parseInt(maxZIndex);
}
/* 显示所有即时贴 */
function showAllNotes(user){
    $.ajax({
    	url:"/note/getAllNotes",
    	dataType: "json",
    	data: "user="+user+"&status=0",
    	success: function(data){
    		appendNote(data);
    	}
    });
}
/* 根据json数据显示和初始化即时贴 */
function appendNote(notes){
	for(var i=0;i<notes.length;i++){
		var note = notes[i];
		appendNewNote(note);
	}
}
/* 新增一个即时贴 */
function appendNewNote(note){
	$("body").append("<div color='"+note.color+"' class='note "+note.color+" style-"+note.style_t+"' id='"+note.id+"' style='width:"+note.width+"px;height:"+note.height+"px;left:"+note.position_x+"px;top:"+note.position_y+"px;z-index:"+note.position_z+";' flag='0'><div class='title'><span class='nadd' title='添加'></span><span class='t' style='left:"+note.title_left+"px;top:"+note.title_top+"px;z-index:"+note.position_z+";'></span><span class='nclose' title='删除'></span></div><div class='pan'><div class='ncontent'>"+note.content+"</div></div><div class='pickcolor'></div><div class='colors'><span class='red'></span><span class='yellow'></span><span class='purple'></span><span class='blue'></span><span class='green'></span></div></div>");
	initNote("#"+note.id);
}
/* 创建即时贴 user:用户ID , 
 * id 创建按钮ID 这个按钮必须要有flag属性，且初始值为0，
 * left，top点击新建按钮生成的即时贴的初始位置,
 * 如果不传入此参数，表示先对与创建按钮进行偏移*/
function create(id,left,top){
	var userId = 1;
	var flag=parseInt($(id).attr("flag"));
	var x=(20*(flag%10))+parseInt($(id).width())*parseInt(flag/10+1)+parseInt($(id).offset().left);
	var y=(20*(flag%10))+parseInt($(id).offset().top);
	if(left){
		x=(20*(flag%10))+parseInt(left);
	}
	if(top){
		y=(20*(flag%10))+parseInt(top);
	}
	//var z=parseInt($(id).css("z-index"));
	//保证点击创建按钮时 创建的note在最顶层
	var z=getMaxZIndex();
	$.ajax({
		type:"get",
		url:"/note/createNew",
		dataType: "json",
		data:{
				"userId":userId,
				"x":x,
				"y":y,
				"z":z
			},
		success: function(data){
			console.log(data);
			appendNewNote(data);
			$(id).attr("flag",flag+1);
    	}
	});
}

/* 初始化即时贴 */
function initNote(id){
   $(id).draggable(
        {cancel:"div.editable"},
        {cursor:"move",distance:20,delay:200},
        {containment:"body", scroll:false},
        {/* 同步即时贴的位置 */
            stop:function(){
            	var id = parseInt($(this).attr("id"));
                var position_x=$(this).offset().left;
                var position_y=$(this).offset().top;
                $(this).attr("flag","0");
                $.ajax({type:"post",url:"/note/updatePosition",data:"id="+id+"&position_x="+position_x+"&position_y="+position_y});
            }
        },
        {/* 开始拖动时候将当前即时贴拿到顶部 */
            start:function(){
            	var positionZ = getMaxZIndex()+1;
                $(this).css("z-index", positionZ);
            }
        }
    );
    /* 单击某个即时贴，将其拿到顶部 */
    $(id).mousedown(function(){
    	var id = parseInt($(this).attr("id"));
    	var positionZ = getMaxZIndex()+1;
        $(this).css("z-index", positionZ);
        $.ajax({type:"post",url:"/note/updatePositionZ",data:"id="+id+"&positionZ="+positionZ,});
    });
    /*鼠标悬停两秒后触发显示工具栏事件，鼠标经过不触发*/
    $(id).hover(function(){
    	time=setTimeout(function(){
    		showTools(id);
    	},400);
    },function(){
    	if(time){
    		clearTimeout(time);
    	}
    	hideTools(id);
    });
    /*点击新建按钮*/
    $(id+" .nadd").click(function(){
    	create(id);
    });
    /*点击删除按钮*/
    $(id+" .nclose").on('click', function(){
    	if(confirm("确定删除？")){
    		remove($(this));
    	}
    });
    /*点击换肤按钮*/
    $(id+" .pickcolor").on('click', function(){
    		$(id+" .colors").toggle();
    });
    $(id+" .colors span").on('click', function(){
    	var color=$(this).attr("class");
    	$(id).removeClass($(id).attr("color")).addClass(color).attr("color",color);
    	$.ajax({type:"post",url:"/note/updateColor",data:"color="+color,});
    	$(this).parent().hide();
    });
    /* 双击编辑 */
    $(id+" .ncontent").dblclick(function(){
    	var id = parseInt($(this).parent().parent().attr("id"));
        var contentSpan = $(this);
        contentSpan.attr("contenteditable", true);
        contentSpan.addClass("editable");
        contentSpan.focus();
        /* 同步即时贴内容 */
        contentSpan.focusout(function(){
            contentSpan.attr("contenteditable", false);
            contentSpan.removeClass("editable");
            var content = contentSpan.html();
            $.ajax({type:"post",url:"/note/updateContent",data:"id="+id+"&content="+content,});
        });
    });
    /* 即时贴可缩放 */
    $(id).resizable(
        {minHeight:150,minWidth:150,maxWidth:300},
        {/* 缩放结束后，同步即时贴尺寸 */
            stop:function(){
            	var id = parseInt($(this).attr("id"));
                var width = parseInt($(this).css("width"));
                var height = parseInt($(this).css("height"));
                var headImg =$(this).children(".title").children(".t");
                var title_left = parseInt(parseInt(width-parseInt(headImg.css("width"))-30)/2);
                console.log(title_left);
                headImg.css("left", title_left+"px");
                $.ajax({type:"post",url:"/note/updateSize",data:"id="+id+"&width="+width+"&height="+height+"&title_left="+title_left,});
            }
        }
    );
}
function remove(id){
	var noteId=id.parent().parent().attr("id");
	$.ajax({type:"get",url:"/note/deleteNote",data:"noteId="+noteId});
	$("#"+noteId).remove();
}
function showTools(id){
	$(id+" .nadd").css("visibility","visible");
	$(id+" .nclose").css("visibility","visible");
	$(id+" .pickcolor").css("visibility","visible");
}

function hideTools(id){
		$(id+" .nadd").css("visibility","hidden");
		$(id+" .nclose").css("visibility","hidden");
		$(id+" .pickcolor").css("visibility","hidden");
}
